﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
using System.Reflection;
using ArtMath.Converter;
using ArtMath.Resource;

namespace ArtMath.Data.Converter
{
    public class RPointSConverter : TypeConverterBase
    {
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string exp = value as string;
            if (exp != null)
            {
                if (context?.Instance != null && !(context.Instance is Array))
                {
                    foreach (PropertyInfo item in context.Instance.GetType().GetProperties())
                    {
                        if (item.Name.Equals(context.PropertyDescriptor.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            RPointS rpt = item.GetValue(context.Instance, null) as RPointS;
                            try
                            {
                                rpt.SetFromString(exp);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, Resources.Translate("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            return rpt;
                        }
                    }
                }
                return null;
            }
            return base.ConvertFrom(context, culture, value);
        }
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value is RPointS)
            {
                string str = value.ToString();
                if (destinationType == typeof(string))
                {
                    return str;
                }
                //else if (destinationType == typeof(InstanceDescriptor))
                //{
                //    return new InstanceDescriptor((value is PPointS ? typeof(PPointS) : typeof(RPointS)).GetConstructor(
                //        new Type[] { typeof(string), typeof(string) }), Regex.Split(str, ", "));
                //}
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, System.Attribute[] attributes)
        {
            if (value is RPointS)
            {
                return TypeDescriptor.GetProperties(value.GetType(), attributes);
            }
            return base.GetProperties(context, value, attributes);
        }
    }
}
